package kr.co.goodwilldd.service.menus.impl;

import java.util.ArrayList;
import java.util.List;

import kr.co.goodwilldd.entity.menus.model.MenuEntity;
import kr.co.goodwilldd.entity.menus.model.MenuItemEntity;

import org.apache.commons.collections.Predicate;

public class MakeMenuUtil {
	
	public static MenuEntity make(List<MenuItemEntity> tree) {
		MenuEntity root = getRoot();
		root.setChildren(getChild(tree, getRootItem()));
		return root;
	}
	
	private static MenuEntity getRoot() {
		MenuEntity root = new MenuEntity();
		MenuItemEntity rootItem = getRootItem();
		root.setMetadata(rootItem);
		root.setTitle(rootItem.getMenuName());
		return root;
	}

	private static MenuItemEntity getRootItem() {
		MenuItemEntity rootItem = new MenuItemEntity();
		rootItem.setMenuName("GreenBeanShop");
		rootItem.setChildSeq(0);
		rootItem.setLinks("/home");
		rootItem.setTypes("ROOT");
		return rootItem;
	}

	@SuppressWarnings("unchecked")
	private static List<MenuEntity> getChild(List<MenuItemEntity> tree,
			final MenuItemEntity rootMetadata) {
		ArrayList<MenuItemEntity> findGroups = new ArrayList<MenuItemEntity>(
				org.apache.commons.collections.CollectionUtils.select(tree,
						new Predicate() {
							@Override
							public boolean evaluate(Object obj) {
								return ((MenuItemEntity) obj).getParentSeq() == rootMetadata
										.getChildSeq();
							}
						}));
		List<MenuEntity> result = new ArrayList<MenuEntity>();
		MenuEntity te = null;
		for (MenuItemEntity item : findGroups) {
			te = new MenuEntity();
			te.setMetadata(item);
			te.setTitle(item.getMenuName());
			te.setChildren(getChild(tree, item));
			result.add(te);
		}
		return result;
	}
}
